package com.dolphin.fxc.auth.work.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dolphin.fxc.auth.work.mapper.SysUserMapper;
import com.dolphin.fxc.auth.work.pojo.entity.SysUser;
import com.dolphin.fxc.auth.work.pojo.entity.auth.AuthUserEntity;
import com.dolphin.fxc.auth.work.pojo.entity.auth.JwtUserEntity;
import com.dolphin.fxc.auth.work.pojo.entity.auth.TokenEntity;
import com.dolphin.fxc.auth.work.service.SysUserService;
import com.dolphin.fxc.auth.work.util.PasswordUtil;
import com.dolphin.fxc.auth.work.util.TokenHelper;
import com.dolphin.fxc.common.work.exception.BizException;
import com.dolphin.fxc.common.work.util.AssertUtil;
import com.dolphin.fxc.common.work.util.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


/**
 * 用户 服务层
 */
@Slf4j
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    private static final String CAPTCHA_PREFIX = "captcha:";
    @Resource
    private SysUserMapper SysUserInfoMapper;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private PasswordUtil passwordUtil;
    @Resource
    private AuthenticationManagerBuilder authenticationManagerBuilder;
    @Resource
    private TokenHelper tokenHelper;


    /**
     * 用户登录
     *
     * @param authUserEntity 用户录入信息
     */
    @Override
    public TokenEntity login(AuthUserEntity authUserEntity) {

//        String code = redisUtil.get(getCaptchaKey(authUserEntity.getUuid()));
//        AssertUtil.hasLength(code, "该验证码不存在或者已失效");
//        AssertUtil.isTrue(code.trim().equals(authUserEntity.getCode().trim()), "验证码错误");
        try {
//            U2FsdGVkX18t844Tc8FaoU1HtQwCUkqZ3iqw7u0mCc8= 前端对密码对称加密
            //String decodePassword = passwordUtil.decodeRsaPassword(authUserEntity);
            String decodePassword = "123456";//todo:密码暂时明文
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(authUserEntity.getUserCode(), decodePassword);
            Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            JwtUserEntity jwtUserEntity = (JwtUserEntity) (authentication.getPrincipal());
            SysUser userEntity = this.getOne(Wrappers.lambdaQuery(SysUser.class).eq(SysUser::getUserCode, jwtUserEntity.getUserCode()));
            AssertUtil.notNull(userEntity, "该用户不存在");
//region todo:先不加获取用户ID
            //获取当前用户的IP
//            HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
//                    .getRequest();
            //String ip = IpUtil.getIpAddr(httpServletRequest);
//            String ip = "220.181.108.177";
//            CityDTO cityDTO = geoIpHelper.getCity(ip);
//            if (Objects.nonNull(cityDTO)) {
//                String city = cityDTO.getCity();
//                validateRemoteLogin(userEntity, city);
//                userEntity.setLastLoginCity(city);
//            }
//endregion
            String token = tokenHelper.generateToken(jwtUserEntity);
//            redisUtil.del(getCaptchaKey(authUserEntity.getUuid()));
//            List<String> roles = jwtUserEntity.getAuthorities().stream()
//                    .map(SimpleGrantedAuthority::getAuthority).collect(Collectors.toList());

            //更新用户的最后登录城市
//            updateLastLoginCity(userEntity);
            return new TokenEntity(jwtUserEntity.getUserCode(), token);
        } catch (Exception e) {
            log.info("登录失败：", e);
            if (e instanceof BizException) {
                throw e;
            }
            throw new BizException(-1, "用户名或密码错误");
        }
    }

    private String getCaptchaKey(String uuid) {
        return String.format("%s%s", CAPTCHA_PREFIX, uuid);
    }


}
